package com.netintech.core.manager.factory;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.TimerTask;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableMap;
import com.netintech.project.monitor.service.SysLoginInfoService;
import com.netintech.project.monitor.service.SysOperLogService;
import com.netintech.project.system.websocket.AlarmWebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.netintech.common.constant.Constants;
import com.netintech.common.utils.LogUtils;
import com.netintech.common.utils.ServletUtils;
import com.netintech.common.utils.ip.AddressUtils;
import com.netintech.common.utils.ip.IpUtils;
import com.netintech.common.utils.spring.SpringUtils;
import com.netintech.project.monitor.domain.SysLogininfor;
import com.netintech.project.monitor.domain.SysOperLog;
import eu.bitwalker.useragentutils.UserAgent;

/**
 * 异步工厂（产生任务用）
 *
 * @author admin
 */
@Slf4j
public class AsyncFactory {
    private static final Logger sys_user_logger = LoggerFactory.getLogger("sys-user");

    private static final String USER_AGENT = "User-Agent";

    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();


    /**
     * 记录登陆信息
     *
     * @param username 用户名
     * @param status   状态
     * @param message  消息
     * @param args     列表
     * @return 任务task
     */
    public static TimerTask recordLogininfor(final String username, final String status, final String message,
                                             final Object... args) {
        final UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader(USER_AGENT));
        final String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
        return new TimerTask() {
            @Override
            public void run() {
                String address = AddressUtils.getRealAddressByIP(ip);
                StringBuilder s = new StringBuilder();
                s.append(LogUtils.getBlock(ip));
                s.append(address);
                s.append(LogUtils.getBlock(username));
                s.append(LogUtils.getBlock(status));
                s.append(LogUtils.getBlock(message));
                // 打印信息到日志
                sys_user_logger.info(s.toString(), args);
                // 获取客户端操作系统
                String os = userAgent.getOperatingSystem().getName();
                // 获取客户端浏览器
                String browser = userAgent.getBrowser().getName();
                // 封装对象
                SysLogininfor logininfor = new SysLogininfor();
                logininfor.setUserName(username);
                logininfor.setIpaddr(ip);
                logininfor.setLoginLocation(address);
                logininfor.setBrowser(browser);
                logininfor.setOs(os);
                logininfor.setMsg(message);
                // 日志状态
                if (Constants.LOGIN_SUCCESS.equals(status) || Constants.LOGOUT.equals(status)) {
                    logininfor.setStatus(Constants.SUCCESS);
                } else if (Constants.LOGIN_FAIL.equals(status)) {
                    logininfor.setStatus(Constants.FAIL);
                }
                // 插入数据
                SpringUtils.getBean(SysLoginInfoService.class).insertLogininfor(logininfor);
            }
        };
    }

    /**
     * 操作日志记录
     *
     * @param operLog 操作日志信息
     * @return 任务task
     */
    public static TimerTask recordOper(final SysOperLog operLog) {
        return new TimerTask() {
            @Override
            public void run() {
                // 远程查询操作地点
                operLog.setOperLocation(AddressUtils.getRealAddressByIP(operLog.getOperIp()));
                SpringUtils.getBean(SysOperLogService.class).insertOperlog(operLog);
            }
        };
    }

//    /**
//     * 报警推送给前端、消息入库
//     *
//     * @return 任务task
//     */
//    public static TimerTask sendAlarmAndSaveNotice(final AlarmHistory alarmHistory, Device device,List<Map<String, String>> receivers) {
//        return new TimerTask() {
//            @Override
//            public void run() {
//                List<String> stringList = SpringUtils.getBean(AlarmService.class).queryShouldPushUId(device);
//                //前端展示转换
//                if (Objects.equals("0", alarmHistory.getAlarmPeopleSex())) {
//                    alarmHistory.setAlarmPeopleSex("女");
//                } else if (Objects.equals("1", alarmHistory.getAlarmPeopleSex())) {
//                    alarmHistory.setAlarmPeopleSex("男");
//                }
//                AlarmCommonsUtils.genAlarmlabels(alarmHistory);
//                //        2. 推送给前端
//                try {
//                    AlarmWebSocketServer.sendInfoByList(OBJECT_MAPPER.writeValueAsString(alarmHistory), stringList);
//                    log.info("向前端发送报警数据成功");
//                } catch (IOException e) {
//                    e.printStackTrace();
//                    log.error("报警信息推送给前端失败" + e.getMessage());
//                }
//            //消息入库
//                try {
//                    SpringUtils.getBean(SysNoticeService.class).addAlarmNotice(alarmHistory, receivers);
//                    log.info("通知表新增报警记录成功");
//                } catch (Exception e) {
//                    log.error("通知表新增报警记录失败" + e.getMessage());
//                    e.printStackTrace();
//                }
//
////                ws推送给对应设备
//                try {
////                    todo 推送的数据目前是报警表的一条记录，后续可能需要转换。推送的对象可能要判断设备类型，推送不同数据。
//                    DeviceInfoWebSocketServer.sendInfo(OBJECT_MAPPER.writeValueAsString(
//                            ImmutableMap.builder()
//                            .put("type",Constants.FACE_ALARM_WS_TYPE)
//                            .put("data",alarmHistory)
//                            .build()
//
//                    ), null);
//                    log.info("向对应设备发送报警数据成功");
//                } catch (JsonProcessingException e) {
//                    log.error("报警信息推送给对应设备失败" + e.getMessage());
//                    e.printStackTrace();
//                }
//            }
//        };
//    }

}
